package com.atguigu.teach.mytask;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

class SqlClass implements Callable<List<String>> {
    private String params;
    public SqlClass(String params) {
        this.params = params;
    }

    @Override
    public List<String> call() throws Exception {
        String[] split = params.split(";");
        List<String> arr = new ArrayList<>();
        for (String rs:
                split) {
            arr.add(rs);
        }
        return  arr;
    }
}
public class ThreadPoolDemo {
    private double size;
    private String sql;
    private static int cpu_num=Runtime.getRuntime().availableProcessors();

    public ThreadPoolDemo(int size, String sql) {
        this.size = size;
        this.sql = sql;
    }

    public double getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getSql() {
        return sql;
    }


    public static int getCpu_num() {
        return cpu_num;
    }

    public static void setCpu_num(int cpu_num) {
        ThreadPoolDemo.cpu_num = cpu_num;
    }
    public String sqlReturn(){
        int max_num=cpu_num*2;
        List<Object> rs = new ArrayList<Object>();
        ThreadPoolExecutor mythreadpool = new ThreadPoolExecutor(
                cpu_num,
                max_num,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(cpu_num),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        int ceil = (int)Math.ceil(size / cpu_num);
        for (int i = 0; i <cpu_num ; i++) {
            String tSql =sql;
            FutureTask<List<String>> futureTask=new FutureTask<>(new SqlClass(tSql ));
            mythreadpool.submit(futureTask);
            try {
                List<String> ccObjects = futureTask.get();
                if(ccObjects.size()>0){
                    rs.add(ccObjects);
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        return rs.toString();

    }

    public static void main(String[] args) {
        int size=10;
        System.out.println("开始");
        String sql="s;e;l;e;c;t;*;f;r;o;m;A;c;c;o;u;n;t";
        ThreadPoolDemo sqlPool = new ThreadPoolDemo(size, sql);
        String rs = sqlPool.sqlReturn();
        System.out.println("结束");
        System.out.println("rs = " + rs);
    }
}
